/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mperon.bean.hb;

import com.mperon.bean.Bean;
import java.util.Date;
import org.apache.commons.lang.ArrayUtils;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreInsertEventListener;
import org.hibernate.event.spi.PreUpdateEvent;
import org.hibernate.event.spi.PreUpdateEventListener;

/**
 *
 * @author Peron
 *
public class HbSaveOrUpdateListener implements PreUpdateEventListener, PreInsertEventListener {

    @Override
    public boolean onPreUpdate(PreUpdateEvent pue) {
        Object object = pue.getEntity();
        if (object instanceof Bean) {
            Bean entity = (Bean) object;
            Date currentTime = new Date();
            String[] propertyNames = pue.getPersister().getEntityMetamodel().getPropertyNames();
            Object[] state = pue.getState();
            setValue(state, propertyNames, "dateUpdated", entity.getDateUpdated(), entity);
            entity.setDateUpdated(currentTime);
            setValue(state, propertyNames, "dateUpdated", currentTime, entity);
        }
        return false;
    }

    @Override
    public boolean onPreInsert(PreInsertEvent pie) {
        Object object = pie.getEntity();
        if (object instanceof Bean) {
            Bean entity = (Bean) object;
            Date currentTime = new Date();
            String[] propertyNames = pie.getPersister().getEntityMetamodel().getPropertyNames();
            Object[] state = pie.getState();
            // updates
            setValue(state, propertyNames, "dateCreated", currentTime, entity);
            setValue(state, propertyNames, "dateUpdated", currentTime, entity);
        }
        return false;
    }

    private void setValue(Object[] currentState, String[] propertyNames, String propertyToSet, Object value, Object entity) {
        int index = ArrayUtils.indexOf(propertyNames, propertyToSet);
        if (index >= 0) {
            currentState[index] = value;
        }
    }
}
* */